package com.haiheng.common.utils

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.PowerManager
import android.util.Log
import com.haiheng.common.bean.ScheduledTaskJob
import com.haiheng.common.bean.ScheduledTaskParas
import com.haiheng.common.bean.ScheduledTasksBean
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.ys.rkapi.MyManager
import java.text.SimpleDateFormat
import java.util.*
import kotlin.system.measureTimeMillis
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.graphics.convertTo
import com.haiheng.common.constant.AppConstant
import com.haiheng.library_base.toast.GsonUtils
import com.haiheng.library_base.utils.DateUtils
import com.haiheng.library_base.utils.SPUtils


/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/5/6 0006
 * @Version: 1.0
 */
object PowerOnOffHelper {


    /**
     * 设置关机或者重启（分为触沃屏和雍慧广告屏）
     * 命令类型 TurnOn=1(开机)、TurnOff=2(关机)、Reboot=3(重启)、Lockscreen=4(锁屏)、TurnOnTheInBookPartition=11(打开书柜分区)
     */
    fun setShutdownOrReboot(context: Context, tasksBean: ScheduledTasksBean): Boolean {

        if (tasksBean.commandName.equals("TurnOff")) {
            //关机
            shutdownByChuWo(context)
            shutdowByYongHui(context)
        } else if (tasksBean.commandName.equals("Reboot")) {
            //重启
            rebootByChuWo(context)
            rebootByYongHui(context)
        } else if (tasksBean.commandName.equals("TurnOn")) {

        }

        return false
    }


    fun shutdownByChuWo(context: Context) {
        //关机
        val manager = MyManager.getInstance(context)
        manager.shutdown()
    }

    fun rebootByChuWo(context: Context) {
        //重启
        val manager = MyManager.getInstance(context)
        manager.reboot()
    }

    /**
     * 雍慧屏关机
     *
     * @param context
     */
    fun shutdowByYongHui(context: Context) {
        val now = Calendar.getInstance()
        var trunOnTask = getTurnOnTask(context)
        if (trunOnTask != null){
            val intent = Intent("android.intent.action.setpoweronoff")
            val timeoffArray = getDateArray(now)
            val timeonArray =  getDateArray(getScheduledTime(trunOnTask))
            intent.putExtra("timeon", timeonArray)
            intent.putExtra("timeoff", timeoffArray)
            intent.putExtra("enable", true) //使能开关机功能，设为 false,则为关闭
            context.sendBroadcast(intent)
            LogWriter.d("雍慧屏设置关机 timeonArray ：${timeonArray.contentToString()}  timeoffArray:${timeoffArray.contentToString()}")
        }

    }

    /**
     * 雍慧屏重启
     *
     * @param context
     */
    fun rebootByYongHui(context: Context) {
        val intent: Intent = Intent("com.android.yf_reboot")
        intent.putExtra("reboot_time", 3)
        context.sendBroadcast(intent)
    }


    /**
     *  设置定时开关机任务
     *
     * @param context
     * @param tasksBean
     * @return
     */
    fun setPowerOnOff(context: Context, tasksBean: ScheduledTasksBean): Boolean {
        if (tasksBean != null && tasksBean.services != null
            && tasksBean.services.size > 0 && tasksBean.services.get(0).properties != null
            && tasksBean.services.get(0).properties.size > 0
            && tasksBean.services.get(0).properties.get(0).content != null
            && tasksBean.services.get(0).properties.get(0).content.jobList != null
            && tasksBean.services.get(0).properties.get(0).content.jobList.size > 0
        ) {
            var jobList = tasksBean.services.get(0).properties.get(0).content.jobList
            var timeOnPars: ScheduledTaskParas? = null
            var timeOffPars: ScheduledTaskParas? = null
            var timeOnTask: ScheduledTaskJob? = null
            var timeOffTask: ScheduledTaskJob? = null
            for (task in jobList) {
                when (task.jobName) {
                    "TurnOn" -> {
                        timeOnPars = task.paras
                        timeOnTask = task
                    }
                    "TurnOff" -> {
                        timeOffPars = task.paras
                        timeOffTask = task
                    }
                }
            }
            if (timeOffPars != null && timeOnPars != null) {
                var timeonArray =
                    timeOnPars.minutes?.get(0)?.let { intArrayOf(timeOnPars.hours[0], it) }
                var timeoffArray =
                    timeOffPars.minutes?.get(0)?.let { intArrayOf(timeOffPars.hours[0], it) }
                var weekdays = intArrayOf(
                    if (timeOffPars.weeks.contains(1)) 1 else 0,
                    if (timeOffPars.weeks.contains(2)) 1 else 0,
                    if (timeOffPars.weeks.contains(3)) 1 else 0,
                    if (timeOffPars.weeks.contains(4)) 1 else 0,
                    if (timeOffPars.weeks.contains(5)) 1 else 0,
                    if (timeOffPars.weeks.contains(6)) 1 else 0,
                    if (timeOffPars.weeks.contains(7)) 1 else 0
                )
                //触沃屏的定时开关机
                var result =
                    setPowerOnOffWithWeeklyByChuwo(context, timeonArray, timeoffArray, weekdays)
                if (timeOnTask != null && timeOffTask != null) {
                    //雍慧屏定时开关机
                    setPowerOnOffYongHui(context, timeOnTask, timeOffTask)
                }
                return result
            }
        }
        return false
    }

    /**
     * 触沃屏的定时开关机
     *
     * @param context
     * @param powerOnTime
     * @param powerOffTime
     * @param weekdays
     * @return
     * 注意点：
    此方法设置的时候，关机时间在前，开机时间在后

     */
    fun setPowerOnOffWithWeeklyByChuwo(
        context: Context, powerOnTime: IntArray?,
        powerOffTime: IntArray?,
        weekdays: IntArray?
    ): Boolean {
        LogUtils.d("设置触沃开关机时间timeonArray ：${powerOnTime.contentToString()}  timeoffArray:${powerOffTime.contentToString()} weekdays:${weekdays.contentToString()}")
        //此方法一天只能有一组时间设入，并且开机时间在前，关机时间在后
        val manager = MyManager.getInstance(context)
//        var powerOnTime = intArrayOf(8,30)
//        var powerOffTime = intArrayOf(18,30)
//        var weekdays = intArrayOf(1,1,1,1,1,0,0);//周一到周日工作状态,1为开机，0为不开机
//        设置上述时间将会在每周一到周五的8:30开机，18:30关机。
        var result = manager.setPowerOnOffWithWeekly(powerOnTime, powerOffTime, weekdays);
        LogWriter.e("设置周模式的定时开关机：$result")
        return result
//        return false
    }

    fun setPowerOnOffByChuwo(context: Context,
                             timeon: Long,
                             timeoff: Long):Boolean {
        try {
            val turnOnDateTime = Calendar.getInstance().apply { timeInMillis = timeon}
            val turnOffDateTime = Calendar.getInstance().apply { timeInMillis = timeoff }
            //触沃广告屏 设置开关机
            val manager = MyManager.getInstance(context)
            //开机时间，年月日时分
//        val timeoffArray = intArrayOf(2023, 4, 24, 17, 23)
//        val timeonArray = intArrayOf(2023, 4, 24, 17, 30)
            var result = manager.setPowerOnOff(getDateArray(turnOnDateTime), getDateArray(turnOffDateTime))
            LogWriter.d("触沃设置开关机 result：${result} turnOnDateTime ：${turnOnDateTime.time}  " +
                    "turnOffDateTime:${turnOffDateTime.time} ")
            return result
        }catch (ex:Exception){
            LogWriter.e("触沃设置开关机异常：${ex.toString()}")
            return false
        }
        return false
    }

    /**
     *  65寸广告屏开关机
     *
     * @param context
     * @param timeon 开机时间
     * @param timeoff 关机时间
     */
    fun setPowerOnOffYongHui(
        context: Context,
        timeon: Long,
        timeoff: Long
    ):Boolean {
        try {
            val turnOnDateTime = Calendar.getInstance().apply { timeInMillis = timeon}
            val turnOffDateTime = Calendar.getInstance().apply { timeInMillis = timeoff }
            //65寸广告屏开关机
            val intent = Intent("android.intent.action.setpoweronoff")
//        val timeoffArray = intArrayOf(2023, 4, 24, 17, 23)
//        val timeonArray = intArrayOf(2023, 4, 24, 17, 30)
            intent.putExtra("timeon", getDateArray(turnOnDateTime))
            intent.putExtra("timeoff", getDateArray(turnOffDateTime))
            intent.putExtra("enable", true) //使能开关机功能，设为 false,则为关闭
            context.sendBroadcast(intent)
            LogWriter.d("雍慧屏设置结束 开关机时间 timeonArray ：${turnOnDateTime.time}  timeoffArray:${turnOffDateTime.time}")
            return true
        }catch (ex:Exception){
            LogWriter.e("雍慧屏设置开关机异常：${ex.toString()}")
            return false
        }
        return false
    }

    /**
     *  雍慧屏定时开关机
     *
     * @param context
     * @param timeOnTask
     * @param timeOffTask
     *
     * 注意事项：
    1、如果每天要定时开关，需要 apk 每次开机的时候去下发下一组的关机时间和开机时间。
    2、不要频繁的下发定时开关的时间，下发多次，也只有最后下发的一组时间会生效。
    3、定时的关机时间和开机时间以及离当前时间需要间隔至少 2 分钟，否则会出现不起作用问题。
    4、设置定时时间一般遵循先关后开的原则。
     */
    fun setPowerOnOffYongHui(
        context: Context,
        timeOnTask: ScheduledTaskJob,
        timeOffTask: ScheduledTaskJob
    ) {
        //65寸广告屏开关机
        // 下一次开机时间
        val nextTimeOnlendar = getScheduledTime(timeOnTask)
        LogUtils.e("下一次开机时间为：" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nextTimeOnlendar.time))
        // 下一次关机时间
        val nextShutdowmCalendar = getScheduledTime(timeOffTask)
        LogUtils.e("下一次关机时间为：" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nextShutdowmCalendar.time))
        val timeonArray = getDateArray(nextTimeOnlendar)
        val timeoffArray = getDateArray(nextShutdowmCalendar)
        //65寸广告屏开关机
        val intent = Intent("android.intent.action.setpoweronoff")
//        val timeoffArray = intArrayOf(2023, 4, 24, 17, 23)
//        val timeonArray = intArrayOf(2023, 4, 24, 17, 30)
        intent.putExtra("timeon", timeonArray)
        intent.putExtra("timeoff", timeoffArray)
        intent.putExtra("enable", true) //使能开关机功能，设为 false,则为关闭
        context.sendBroadcast(intent)
        LogWriter.d("雍慧屏设置开关机时间 timeonArray ：${timeonArray.contentToString()}  timeoffArray:${timeoffArray.contentToString()}")
    }

    fun getDateArray(calendar: Calendar): IntArray {
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1  // 月份从0开始，需要加1
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val second = calendar.get(Calendar.SECOND)
        return intArrayOf(year, month, day, hourOfDay, minute)
    }

    fun getNextScheduledTime(cronExpression: String, currentTime: Long): Long {
        // "cron":"0 17 18 ? * 2,5,6",
        val cronParams = cronExpression.split(" ")
        val calendar = Calendar.getInstance().apply { timeInMillis = currentTime }

        // 解析 cron 表达式中的星号，包括年份（默认为今年）
        val year = calendar.get(Calendar.YEAR)
        val cronYear =
            if (cronParams.size > 6 && cronParams[6] != "?") cronParams[6] else year.toString()

        // 解析 cron 表达式中的时间参数
        val cronMinute = cronParams[1].toInt()
        val cronHour = cronParams[2].toInt()

        // 解析 cron 表达式中的星期参数
        val cronWeek = cronParams[5]
        val weekdays = if (cronWeek == "?") null else cronWeek.split(",").map { it.toInt() }

        // 计算下一个定时时间
        while (true) {
            calendar.apply {
                add(Calendar.DAY_OF_MONTH, 1) // 每次加一天
                set(Calendar.HOUR_OF_DAY, cronHour)
                set(Calendar.MINUTE, cronMinute)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }

            // 判断是否符合星期要求
            if (weekdays == null || weekdays.contains(calendar.get(Calendar.DAY_OF_WEEK))) {
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                val scheduledTime = dateFormat.parse(
                    "$cronYear-${calendar.get(Calendar.MONTH) + 1}-${
                        calendar.get(Calendar.DAY_OF_MONTH)
                    } ${cronHour}:${cronMinute}:00"
                )!!.time
                if (scheduledTime > currentTime) {
                    return scheduledTime
                }
            }
        }
    }


    fun getScheduledTime(taskParas: ScheduledTaskJob): Calendar {
        val shutdownTime = parseShutdownTime(taskParas) // 解析关机时间

        val now = Calendar.getInstance()
        val shutdownToday = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, shutdownTime.get(Calendar.HOUR_OF_DAY))
            set(Calendar.MINUTE, shutdownTime.get(Calendar.MINUTE))
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }

        if (shutdownToday.before(now)) { // 开关机时间已经过了，则返回下一次开关机时间
//            shutdownToday.add(Calendar.DAY_OF_MONTH, 1)
            return Calendar.getInstance().apply {
                timeInMillis = getNextScheduledTime(taskParas.cron,System.currentTimeMillis())
            }
        }else {
            //如果时间点没过，如果是当日星期，则返回今天时间，如果不符合当前星期，也返回下一次关机时间
            val cronParams = taskParas.cron.split(" ")
            // 解析 cron 表达式中的星期参数
            val cronWeek = cronParams[5]
            val weekdays = if (cronWeek == "?") null else cronWeek.split(",").map { it.toInt() }
            if (weekdays == null || weekdays.contains(shutdownToday.get(Calendar.DAY_OF_WEEK))) {
                return  shutdownToday
            }else{
                return Calendar.getInstance().apply {
                    timeInMillis = getNextScheduledTime(taskParas.cron,System.currentTimeMillis())
                }
            }
        }

        return shutdownToday
    }

    /**
     *  解析时间
     *
     * @param taskParas
     * @return
     * {
    "jobName":"TurnOn",
    "jobDescription":"TurnOn",
    "cron":"0 41 15 ? * 2",
    "paras":{
    "weeks":[
    1
    ],
    "days":null,
    "hours":Array[1],
    "minutes":Array[1]
    }
    }
     */
    private fun parseShutdownTime(taskParas: ScheduledTaskJob): Calendar {
        //0 41 15 ? * 2
        val paras = taskParas.paras ?: return Calendar.getInstance()

        val hours = paras.hours?.getOrNull(0) ?: return Calendar.getInstance()
        val minutes = paras.minutes?.getOrNull(0) ?: return Calendar.getInstance()

        val shutdownTime = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
            set(Calendar.HOUR_OF_DAY, hours)
            set(Calendar.MINUTE, minutes)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        return shutdownTime
    }


    fun getTurnOnTask(context: Context):ScheduledTaskJob? {
        var taskString = SPUtils.getInstance().getString(AppConstant.SP_SCHEDULED_TASK)
        var timeOnTask: ScheduledTaskJob? = null
        var timeOffTask: ScheduledTaskJob? = null
        if (taskString.isNotBlank()){
            try {
                var tasksBean = GsonUtils.fromJson(taskString, ScheduledTasksBean::class.java)
                if (tasksBean != null && tasksBean.services != null
                    && tasksBean.services.size > 0 && tasksBean.services.get(0).properties != null
                    && tasksBean.services.get(0).properties.size > 0
                    && tasksBean.services.get(0).properties.get(0).content != null
                    && tasksBean.services.get(0).properties.get(0).content.jobList != null
                    && tasksBean.services.get(0).properties.get(0).content.jobList.size > 0
                ) {
                    var jobList = tasksBean.services.get(0).properties.get(0).content.jobList
                    for (task in jobList) {
                        when (task.jobName) {
                            "TurnOn" -> {
                                timeOnTask = task
                            }
                            "TurnOff" -> {
                                timeOffTask = task
                            }
                        }
                    }
                }
            }catch (ex:Exception){
                LogWriter.e("getTurnOffTask 定时任务解析异常:${ex.message}")
            }
        }
        return  timeOnTask
    }
    fun getCurrentScheduledTimePair(config: String): Pair<Long, Long> {
        try {
            var currentTime =  System.currentTimeMillis()
            var tasksBean = GsonUtils.fromJson(config, ScheduledTasksBean::class.java)
            if (tasksBean != null && tasksBean.services != null
                && tasksBean.services.size > 0 && tasksBean.services.get(0).properties != null
                && tasksBean.services.get(0).properties.size > 0
                && tasksBean.services.get(0).properties.get(0).content != null
                && tasksBean.services.get(0).properties.get(0).content.jobList != null
                && tasksBean.services.get(0).properties.get(0).content.jobList.size > 0
            ) {
                val jobList = tasksBean.services.first().properties.first().content.jobList
                var turnOffTime  = calculateNextTurnOffScheduledTime(currentTime,jobList)
                // 初始化 Pair 对象
                var turnOnTime = calculateNextTurnOnScheduledTime(currentTime,jobList,turnOffTime)
                // 输出当前要设置的定时任务的开机时间和关机时间
                val turnOnDateTime = Calendar.getInstance().apply { timeInMillis = turnOnTime}
                val turnOffDateTime = Calendar.getInstance().apply { timeInMillis = turnOffTime }
                println("当前要设置的定时任务：开机时间是：${PowerOnOffHelper.getDateArray(turnOnDateTime).contentToString()}，" +
                        "关机时间是：${PowerOnOffHelper.getDateArray(turnOffDateTime).contentToString()}")
                return turnOnTime to turnOffTime
            }
        }catch (ex:Exception){
            println("getTurnOffTask 定时任务解析异常:${ex.message}")
        }
        return 0L to 0
    }

    fun setCurrentScheduledTimePair(context: Context,config: String): Boolean {
        // 获取当前要设置的定时任务的开机时间和关机时间
        val timePair = PowerOnOffHelper.getCurrentScheduledTimePair(config)
        //设置触沃广告屏 开关机
        var chuwoResul = setPowerOnOffByChuwo(context,timePair.first,timePair.second)
        //设置56寸 雍慧广告屏开关机
        var ronghuiResul = setPowerOnOffYongHui(context,timePair.first,timePair.second)
        LogUtils.d("设置开关机结果 chuwoResul :：${chuwoResul} ronghuiResul:${ronghuiResul}")
       return chuwoResul || ronghuiResul
    }

    private fun getCalendarDayOfWeek(calendar: Calendar):Int{
        var dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1
        if (dayOfWeek == 0) {
            dayOfWeek = 7
        }
        return dayOfWeek
    }

    /**
     *  计算下次开机时间
     *
     * @param currentTime
     * @param jobList
     * @param turnOffTime
     * @return
     */
    private fun calculateNextTurnOnScheduledTime(
        currentTime: Long,
        jobList: List<ScheduledTaskJob>,
        turnOffTime:Long
    ): Long {
        var isNoExitJob = true//当天没有设置定时任务
        val calendar = Calendar.getInstance().apply { timeInMillis = currentTime }
        for (i in 0 until jobList.size) {
            val currentJob = jobList[i]
            val hour = currentJob.paras.hours.first()
            val minute = currentJob.paras.minutes.first()
            val cronWeek = currentJob.cron.split(" ")[5]
            val weeks = currentJob.paras.weeks
            calendar.apply {
                set(Calendar.HOUR_OF_DAY, hour)
                set(Calendar.MINUTE, minute)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }
            var currentDayOfWeek = getCalendarDayOfWeek(calendar)
            println("当前星期："+currentDayOfWeek)
            // 如果是当前星期 任务星期包含当前时间
            if (weeks.contains(getCalendarDayOfWeek(calendar))){
//            if (cronWeek.contains(calendar.get(Calendar.DAY_OF_WEEK).toString())) {
//                if (currentJob.paras.weeks.contains(calendar.get(Calendar.DAY_OF_WEEK))) {
                when(currentJob.jobName){
                    "TurnOn"->{//计算开机时间
                        isNoExitJob = false
                        println("今天开机任务：${currentJob.jobName} ${currentJob.cron} ")
                        // 1.如果当天任务开机时间已经过了，则获取下一个任务开机时间，
                        // 2.并且如果下一个开机时间比在关机时间之前，则再获取下一个任务开机时间
                        if (calendar.timeInMillis < currentTime){
                            val nextJob = getNextJobByWeek(calendar,currentJob,jobList)
                            val nextHour = nextJob.paras.hours.first()
                            val nextMinute = nextJob.paras.minutes.first()
//                            val nextCronWeek = nextJob.cron.split(" ")[5]
                            val nextWeeks = nextJob.paras.weeks
                            calendar.apply {
                                set(Calendar.HOUR_OF_DAY, nextHour)
                                set(Calendar.MINUTE, nextMinute)
                                set(Calendar.SECOND, 0)
                                set(Calendar.MILLISECOND, 0)
                            }
                            // 如果是当前星期 任务星期包含当前时间
//                            while (!nextWeeks.contains(getCalendarDayOfWeek(calendar))) {
////                            while (!nextCronWeek.contains(calendar.get(Calendar.DAY_OF_WEEK).toString())) {
//                                calendar.add(Calendar.DAY_OF_MONTH, 1)
//                            }
                            if (calendar.timeInMillis < turnOffTime){
                                val nextTwoJob = getNextJobByWeek(calendar,nextJob,jobList)
                                val nextTwoHour = nextTwoJob.paras.hours.first()
                                val nextTwoMinute = nextTwoJob.paras.minutes.first()
                                val nextTwoCronWeek = nextTwoJob.cron.split(" ")[5]
                                val nextTwoWeeks = nextTwoJob.paras.weeks
                                calendar.apply {
                                    set(Calendar.HOUR_OF_DAY, nextTwoHour)
                                    set(Calendar.MINUTE, nextTwoMinute)
                                    set(Calendar.SECOND, 0)
                                    set(Calendar.MILLISECOND, 0)
                                }

//                                while (!nextTwoWeeks.contains(getCalendarDayOfWeek(calendar))) {
////                                while (!nextTwoCronWeek.contains(calendar.get(Calendar.DAY_OF_WEEK).toString())) {
//                                    calendar.add(Calendar.DAY_OF_MONTH, 1)
//                                }
                            }
                        }else{//如果当天配置开机时间没有到，并且配置开机时间在关机时间之前，这开机时间为下一个任务的开机时间
                            //如果开机时间再关机时间之后，则当前配置开机时间就是当前设置时间
                            if (calendar.timeInMillis < turnOffTime){
                                val nextJob = getNextJobByWeek(calendar,currentJob,jobList)
                                val nextHour = nextJob.paras.hours.first()
                                val nextMinute = nextJob.paras.minutes.first()
                                val nextCronWeek = nextJob.cron.split(" ")[5]
                                val nextWeeks = nextJob.paras.weeks
                                calendar.apply {
                                    set(Calendar.HOUR_OF_DAY, nextHour)
                                    set(Calendar.MINUTE, nextMinute)
                                    set(Calendar.SECOND, 0)
                                    set(Calendar.MILLISECOND, 0)
                                }
//                                while (!nextWeeks.contains(getCalendarDayOfWeek(calendar))) {
////                                while (!nextCronWeek.contains(calendar.get(Calendar.DAY_OF_WEEK).toString())) {
//                                    calendar.add(Calendar.DAY_OF_MONTH, 1)
//                                }
                            }
                        }
                        return calendar.timeInMillis
                    }
                }
            }
        }
        if (isNoExitJob){
            println("当天没有设置任务，直接去设置下一天的定时任务")
            calendar.apply {
                set(Calendar.HOUR_OF_DAY, 0)
                set(Calendar.MINUTE, 0)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            return calculateNextTurnOnScheduledTime(calendar.timeInMillis,jobList,turnOffTime)
        }
        return calendar.timeInMillis
    }
    private fun calculateNextTurnOffScheduledTime(
        currentTime: Long,
        jobList: List<ScheduledTaskJob>,
    ): Long {
        var isNoExitJob = true//当天没有设置定时任务
        val calendar = Calendar.getInstance().apply { timeInMillis = currentTime }
        for (i in 0 until jobList.size) {
            val currentJob = jobList[i]
            val hour = currentJob.paras.hours.first()
            val minute = currentJob.paras.minutes.first()
            val weekdays = currentJob.paras.weeks
            calendar.apply {
                set(Calendar.HOUR_OF_DAY, hour)
                set(Calendar.MINUTE, minute)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }
            // 如果是当前星期 任务星期包含当前时间
            if (weekdays.contains(getCalendarDayOfWeek(calendar))) {
                when(currentJob.jobName){
                    "TurnOff" ->{// 计算关机任务的时间
                        isNoExitJob = false
                        println("当前关机任务：${currentJob.jobName} ${currentJob.cron} ")
                        //如果当天任务关机时间已经过了，则获取下一个任务关机时间
                        println("calendar:${calendar.timeInMillis} currentTime:${currentTime} ")
                        if (calendar.timeInMillis < currentTime){
                            println("当天关机任务时间已经过了")
                            val nextJob = getNextJobByWeek(calendar,currentJob,jobList)
                            val nextHour = nextJob.paras.hours.first()
                            val nextMinute = nextJob.paras.minutes.first()
                            val nextWeeks = nextJob.paras.weeks
                            calendar.apply {
                                set(Calendar.HOUR_OF_DAY, nextHour)
                                set(Calendar.MINUTE, nextMinute)
                                set(Calendar.SECOND, 0)
                                set(Calendar.MILLISECOND, 0)
                            }
                        }else{//如果当天关机时间还没过，则关机时间就是当前任务关机时间
                            println("当天关机任务时间还没到")
                        }
                        return calendar.timeInMillis
                    }
                }
            }
        }
        //任务列表中没有当天设置的任务，直接设置下一天的任务
        if (isNoExitJob){
            println("当天没有设置任务，直接设置下一天的定时任务")
            calendar.apply {
                set(Calendar.HOUR_OF_DAY, 0)
                set(Calendar.MINUTE, 0)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            return calculateNextTurnOffScheduledTime(calendar.timeInMillis,jobList)
        }
        return calendar.timeInMillis
    }



    private fun getNextJobByWeek(
        calendar:Calendar,
        job: ScheduledTaskJob,
        jobList: List<ScheduledTaskJob>
    ): ScheduledTaskJob {
        //如果当前任务就包含下一个任务的星期，则说明当前任务时间和下一个任务时间一样
        calendar.add(Calendar.DAY_OF_WEEK,1)
        val currentWeeks = job.paras.weeks
        val nextDayWeek = getCalendarDayOfWeek(calendar)
        println("下一个星期："+nextDayWeek)
//        if (currentWeeks.contains(getCalendarDayOfWeek(calendar))){
//            println("下一个任务：${job.jobName} ${job.cron} ")
//            return job
//        }
        val currentIndex = jobList.indexOf(job)
        for (i in 0  until jobList.size) {
            val nextJob = jobList[i]
            val nextJobWeeks = nextJob.paras.weeks
            if (nextJob.jobName == job.jobName && nextJobWeeks.contains(nextDayWeek) ) {
                println("找到当前下一个任务：${nextJob.jobName} ${nextJob.cron} ")
                return nextJob
            }
        }
        //下一天没有配置对应任务，继续循环查找
        return getNextJobByWeek(calendar,job,jobList)
//        return jobList.first { it.jobName == job.jobName}
    }
}